// 手机端专用JavaScript
let priceChart;
let updateInterval;
let countdownInterval;
let ws = null;
let wsConnected = false;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;

// WebSocket连接函数
function connectWebSocket() {
    if (ws && ws.readyState === WebSocket.OPEN) {
        console.log('WebSocket已连接');
        return;
    }
    
    try {
        // 获取WebSocket服务器配置
        fetch('ajax/get_websocket_config.php')
            .then(response => response.json())
            .then(config => {
                if (config.success && config.host) {
                    // 构建完整的WebSocket URL
                    const wsUrl = `ws://${config.host}:${config.port || 8080}`;
                    console.log('正在连接WebSocket服务器:', wsUrl);
                    ws = new WebSocket(wsUrl);
                    
                    ws.onopen = function() {
                        console.log('WebSocket连接已建立');
                        wsConnected = true;
                        reconnectAttempts = 0;
                        showNotification('实时连接已建立', 'success');
                        updateWebSocketStatus('connected', '已连接');
                        
                        // 发送客户端信息
                        ws.send(JSON.stringify({
                            type: 'client_info',
                            user_id: window.userId || null,
                            username: window.username || 'guest'
                        }));
                    };
                    
                    ws.onmessage = function(event) {
                        try {
                            const data = JSON.parse(event.data);
                            
                            switch(data.type) {
                                case 'price_update':
                                    if (data.current_price) {
                                        updatePriceDisplay(data.current_price);
                                    }
                                    if (data.price_history) {
                                        updateChart(data.price_history);
                                    } else {
                                    }
                                    break;
                                    
                                case 'round_update':
                                    if (data.round_info) {
                                        updateRoundInfo(data.round_info);
                                    }
                                    break;
                                    
                                case 'transaction_update':
                                    if (data.transactions) {
                                        // 更新市场交易记录
                                        updateMarketTransactions(data.transactions);
                                    }
                                    break;
                                    
                                case 'user_update':
                                    if (data.user_balance !== undefined) {
                                        updateUserBalance(data.user_balance, data.user_frozen_profit || 0);
                                    }
                                    if (data.positions) {
                                        updatePositions(data.positions);
                                    }
                                    break;
                                    
                                default:
                                    console.log('未知消息类型:', data.type);
                            }
                        } catch (error) {
                            console.error('解析WebSocket消息失败:', error);
                        }
                    };
                    
                    ws.onclose = function() {
                        console.log('WebSocket连接已关闭');
                        wsConnected = false;
                        ws = null;
                        
                        // 自动重连
                        if (reconnectAttempts < maxReconnectAttempts) {
                            reconnectAttempts++;
                            const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
                            console.log(`${delay}ms后尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})`);
                            
                            setTimeout(() => {
                                connectWebSocket();
                            }, delay);
                        } else {
                            console.error('WebSocket重连失败，已达到最大重试次数');
                            showNotification('实时连接失败，将使用备用更新方式', 'warning');
                        }
                    };
                    
                    ws.onerror = function(error) {
                        console.error('WebSocket错误:', error);
                        wsConnected = false;
                    };
                    
                } else {
                    console.error('WebSocket配置获取失败:', config.message);
                    showNotification('无法获取WebSocket配置', 'error');
                }
            })
            .catch(error => {
                console.error('获取WebSocket配置失败:', error);
                showNotification('网络错误，无法连接实时服务', 'error');
            });
            
    } catch (error) {
        console.error('WebSocket连接失败:', error);
        wsConnected = false;
    }
}

// 更新市场交易记录
function updateMarketTransactions(transactions) {
    const container = document.getElementById('market-trades');
    if (!container) return;
    
    if (transactions.length === 0) {
        container.innerHTML = '<div class="loading-text">暂无交易记录</div>';
        return;
    }
    
    // 显示最新的10条记录
    const latestTransactions = transactions.slice(0, 10);
    
    container.innerHTML = latestTransactions.map(trade => {
        const typeClass = trade.type === 'buy' ? 'trade-buy' : 'trade-sell';
        const typeText = trade.type === 'buy' ? '买入' : '卖出';
        
        return `
            <div class="market-trade-item">
                <div class="trade-info">
                    <span class="${typeClass}">${typeText}</span>
                    <span class="trade-user">${trade.username}</span>
                    <span class="trade-time" data-original-time="${trade.transaction_time}">${trade.transaction_time}</span>
                </div>
                <div class="trade-details">
                    <span class="trade-amount">¥${trade.amount.toFixed(2)}</span>
                    <span class="trade-quantity">${trade.quantity.toFixed(4)}股</span>
                </div>
            </div>
        `;
    }).join('');
    
    // 启动时间更新定时器
    startTimeUpdateTimer();
}

// 启动时间更新定时器
function startTimeUpdateTimer() {
    // 清除之前的定时器
    if (window.timeUpdateTimer) {
        clearInterval(window.timeUpdateTimer);
    }
    
    // 每秒更新一次交易时间显示
    window.timeUpdateTimer = setInterval(() => {
        const timeElements = document.querySelectorAll('.trade-time');
        timeElements.forEach(element => {
            const originalTime = element.getAttribute('data-original-time');
            if (originalTime) {
                const timeAgo = new Date(originalTime);
                element.textContent = timeAgo;
            }
        });
    }, 1000);
}

// 获取相对时间
function getTimeAgo(timeString) {
    // 如果只是时间格式（如 19:29:15），则直接返回
    if (timeString && timeString.length <= 8 && timeString.includes(':')) {
        return timeString;
    }
    
    // 如果是完整的日期时间，则计算相对时间
    try {
        const date = new Date(timeString);
        if (isNaN(date.getTime())) {
            return timeString; // 如果解析失败，直接返回原值
        }
        
        const now = new Date();
        const diffInSeconds = Math.floor((now - date) / 1000);
        
        if (diffInSeconds < 60) {
            return '刚刚';
        } else if (diffInSeconds < 3600) {
            const minutes = Math.floor(diffInSeconds / 60);
            return `${minutes}分钟前`;
        } else if (diffInSeconds < 86400) {
            const hours = Math.floor(diffInSeconds / 3600);
            return `${hours}小时前`;
        } else {
            const days = Math.floor(diffInSeconds / 86400);
            return `${days}天前`;
        }
    } catch (error) {
        console.error('时间解析错误:', error);
        return timeString; // 出错时返回原值
    }
}

// 初始化手机端图表
function initMobileChart(priceHistory) {
    const ctx = document.getElementById('priceChart').getContext('2d');
    
    const labels = priceHistory.map(item => {
        const date = new Date(item.timestamp);
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    });
    
    const prices = priceHistory.map(item => parseFloat(item.price));
    
    // 计算价格范围
    const minPrice = Math.min(...prices);
    const maxPrice = Math.max(...prices);
    const padding = (maxPrice - minPrice) * 0.1;
    
    priceChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '价格',
                data: prices,
                borderColor: '#4caf50',
                backgroundColor: 'rgba(76, 175, 80, 0.1)',
                borderWidth: 3,
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#4caf50',
                pointBorderColor: '#ffffff',
                pointBorderWidth: 2,
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
            scales: {
                y: {
                    min: Math.max(1, minPrice - padding),
                    max: maxPrice + padding,
                    grid: {
                        color: 'rgba(0,0,0,0.05)'
                    },
                    ticks: {
                        color: '#666',
                        font: {
                            size: 12
                        },
                        callback: function(value) {
                            return '¥' + value.toFixed(2);
                        }
                    }
                },
                x: {
                    grid: {
                        color: 'rgba(0,0,0,0.05)'
                    },
                    ticks: {
                        color: '#666',
                        font: {
                            size: 11
                        },
                        maxTicksLimit: 6
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(0,0,0,0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: '#4caf50',
                    borderWidth: 1,
                    cornerRadius: 8,
                    displayColors: false,
                    callbacks: {
                        title: function(context) {
                            return '时间: ' + context[0].label;
                        },
                        label: function(context) {
                            return '价格: ¥' + context.parsed.y.toFixed(2);
                        }
                    }
                }
            },
            animation: {
                duration: 750,
                easing: 'easeInOutQuart'
            }
        }
    });
}

// 启动实时更新
function startRealTimeUpdates() {
    // 启动WebSocket连接
    connectWebSocket();
    
    // 启动倒计时
    startCountdown();
    
    // 加载市场交易记录（如果在交易页面）
    if (document.querySelector('.nav-item.active').dataset.section === 'trading') {
        loadRoundTransactions();
    }
    
    // 备用：每30秒更新一次市场交易记录（当WebSocket不可用时）
    setInterval(() => {
        if (!wsConnected && document.querySelector('.nav-item.active').dataset.section === 'trading') {
            loadRoundTransactions();
        }
    }, 30000);
}

// 更新游戏数据
function updateGameData() {
    fetch('ajax/update_game.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新基本游戏数据（无论是否登录都更新）
                updatePriceDisplay(data.current_price);
                updateChart(data.price_history);
                updateRoundInfo(data.round_info);
                
                // 仅在用户已登录时更新用户相关数据
                if (data.is_logged_in) {
                    updateUserBalance(data.user_balance, data.user_frozen_profit);
                    updatePositions(data.positions);
                }
            }
        })
        .catch(error => {
            console.error('更新数据失败:', error);
        });
}

// 更新价格显示
function updatePriceDisplay(newPrice) {
    const priceElement = document.getElementById('current-price');
    const currentPrice = parseFloat(priceElement.textContent.replace('¥', '').replace(',', ''));
    
    priceElement.textContent = '¥' + parseFloat(newPrice).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
    
    // 添加价格变化动画和颜色
    priceElement.classList.remove('updated');
    setTimeout(() => {
        priceElement.classList.add('updated');
    }, 10);
    
    if (newPrice > currentPrice) {
        priceElement.style.color = '#4caf50';
    } else if (newPrice < currentPrice) {
        priceElement.style.color = '#f44336';
    } else {
        priceElement.style.color = '#4caf50';
    }
    
    // 实时更新持仓盈亏
    updatePositionsProfit(newPrice);
}

// 更新图表
function updateChart(priceHistory) {
    if (!priceChart) {
        console.warn('priceChart未初始化');
        return;
    }
    if (!priceHistory) {
        console.warn('priceHistory为空');
        return;
    }
    
    const labels = priceHistory.map(item => {
        const date = new Date(item.timestamp);
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    });
    
    const prices = priceHistory.map(item => parseFloat(item.price));
    
    priceChart.data.labels = labels;
    priceChart.data.datasets[0].data = prices;
    
    // 动态调整Y轴范围
    const minPrice = Math.min(...prices);
    const maxPrice = Math.max(...prices);
    const padding = (maxPrice - minPrice) * 0.1;
    
    priceChart.options.scales.y.min = Math.max(1, minPrice - padding);
    priceChart.options.scales.y.max = maxPrice + padding;
    
    priceChart.update('none');
}

// 更新轮次信息
function updateRoundInfo(roundInfo) {
    document.getElementById('round-number').textContent = roundInfo.round_number;
    
    // 根据状态生成状态文本
    let statusText = '';
    const now = Math.floor(Date.now() / 1000);
    const roundStart = Math.floor(new Date(roundInfo.start_time).getTime() / 1000);
    const tradingEnd = roundStart + (10 * 60); // 10分钟交易时间
    const roundEnd = Math.floor(new Date(roundInfo.end_time).getTime() / 1000);
    
    if (now < roundStart) {
        statusText = '等待开始';
    } else if (now <= tradingEnd) {
        statusText = '交易中';
    } else if (now <= roundEnd) {
        statusText = '休市中';
    } else {
        statusText = '已结束';
    }
    
    document.getElementById('round-status').textContent = statusText;
    
    // 保存轮次信息到全局变量
    window.currentRoundInfo = roundInfo;
    
    updateCountdown(roundInfo);
}

// 更新用户余额
function updateUserBalance(balance, frozenProfit) {
    document.getElementById('balance').textContent = parseFloat(balance).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

// 更新持仓信息
function updatePositions(positions) {
    const positionsContainer = document.getElementById('positions-list');
    const positionsCount = document.querySelector('.positions-count');
    
    positionsCount.textContent = positions.length + '笔';
    
    if (!positions || positions.length === 0) {
        positionsContainer.innerHTML = `
            <div class="empty-state">
                <p>暂无持仓</p>
                <p class="tip">买入后持仓将显示在这里</p>
            </div>
        `;
        return;
    }
    
    const currentPrice = parseFloat(document.getElementById('current-price').textContent.replace('¥', '').replace(',', ''));
    
    positionsContainer.innerHTML = positions.map(position => {
        const profit = (currentPrice - parseFloat(position.purchase_price)) * parseFloat(position.quantity);
        const profitClass = profit >= 0 ? 'profit-positive' : 'profit-negative';
        
        return `
            <div class="position-card" data-position-id="${position.id}">
                <div class="position-header">
                    <span class="round-badge">第${position.round_number}轮</span>
                    <button class="sell-btn" onclick="sellPosition(${position.id})">卖出</button>
                </div>
                <div class="position-details">
                    <div class="detail-item">
                        <span class="label">数量</span>
                        <span class="value">${parseFloat(position.quantity).toFixed(4)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">成本</span>
                        <span class="value">¥${parseFloat(position.purchase_price).toFixed(2)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">盈亏</span>
                        <span class="value profit ${profitClass}" data-purchase-price="${position.purchase_price}" data-quantity="${position.quantity}">¥${profit.toFixed(2)}</span>
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

// 实时更新持仓盈亏
function updatePositionsProfit(currentPrice) {
    const profitElements = document.querySelectorAll('.position-card .profit');
    
    profitElements.forEach(element => {
        const purchasePrice = parseFloat(element.getAttribute('data-purchase-price'));
        const quantity = parseFloat(element.getAttribute('data-quantity'));
        
        if (purchasePrice && quantity) {
            const profit = (currentPrice - purchasePrice) * quantity;
            const profitClass = profit >= 0 ? 'profit-positive' : 'profit-negative';
            
            // 更新盈亏数值和样式
            element.textContent = '¥' + profit.toFixed(2);
            element.className = `value profit ${profitClass}`;
            
            // 添加更新动画
            element.classList.add('profit-updated');
            setTimeout(() => {
                element.classList.remove('profit-updated');
            }, 1000);
        }
    });
}

// 倒计时功能
function startCountdown() {
    // 清除之前的定时器
    if (countdownInterval) {
        clearInterval(countdownInterval);
    }
    
    // 立即执行一次倒计时更新
    updateCountdownDisplay();
    
    // 每秒更新一次倒计时
    countdownInterval = setInterval(() => {
        updateCountdownDisplay();
    }, 1000);
    
    
    // 添加定时器状态检查
    setTimeout(() => {
        if (countdownInterval) {
        } else {
            console.error('倒计时定时器状态检查 - 异常，定时器被清除');
        }
    }, 5000);
}

function updateCountdown(roundInfo) {
    // 保存轮次信息到全局变量，供倒计时使用
    window.currentRoundInfo = roundInfo;
    
    // 立即更新一次倒计时显示
    updateCountdownDisplay();
    
}

function updateCountdownDisplay() {
    try {
        // 检查是否有轮次信息
        if (!window.currentRoundInfo) {
            document.getElementById('countdown').textContent = '--:--';
            return;
        }
        
        const roundInfo = window.currentRoundInfo;
    const now = Math.floor(Date.now() / 1000);
    const roundStart = Math.floor(new Date(roundInfo.start_time).getTime() / 1000);
        const tradingEnd = roundStart + (10 * 60); // 10分钟交易时间
    const roundEnd = Math.floor(new Date(roundInfo.end_time).getTime() / 1000);
    
    let remainingTime;
        let statusText = '';
        
        if (now < roundStart) {
            // 轮次还未开始
            remainingTime = roundStart - now;
            statusText = '等待开始';
        } else if (now <= tradingEnd) {
            // 交易时间内
        remainingTime = tradingEnd - now;
            statusText = '交易中';
    } else if (now <= roundEnd) {
            // 休市时间
        remainingTime = roundEnd - now;
            statusText = '休市中';
    } else {
            // 轮次已结束
        remainingTime = 0;
            statusText = '已结束';
    }
    
        // 更新倒计时显示
        if (remainingTime > 0) {
    const minutes = Math.floor(remainingTime / 60);
    const seconds = remainingTime % 60;
            const timeText = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            document.getElementById('countdown').textContent = timeText;
            document.getElementById('round-status').textContent = statusText;
            
            // 根据剩余时间添加颜色提示
            const countdownElement = document.getElementById('countdown');
            if (remainingTime <= 60) { // 最后1分钟
                countdownElement.style.color = '#f44336'; // 红色
                countdownElement.style.fontWeight = 'bold';
            } else if (remainingTime <= 300) { // 最后5分钟
                countdownElement.style.color = '#ff9800'; // 橙色
            } else {
                countdownElement.style.color = '#333'; // 正常颜色
                countdownElement.style.fontWeight = 'normal';
            }
            
        } else {
            document.getElementById('countdown').textContent = '00:00';
            document.getElementById('round-status').textContent = statusText;
            document.getElementById('countdown').style.color = '#999';
        }
    } catch (error) {
        console.error('倒计时更新出错:', error);
        // 出错时尝试重新启动倒计时
        if (countdownInterval) {
            clearInterval(countdownInterval);
            countdownInterval = null;
        }
        // 延迟1秒后重新启动
        setTimeout(() => {
            if (window.currentRoundInfo) {
                startCountdown();
            }
        }, 1000);
    }
}

// 交易表单处理
document.addEventListener('DOMContentLoaded', function() {
    const tradingForm = document.getElementById('trading-form');
    const amountInput = document.getElementById('amount');
    const quickAmountBtns = document.querySelectorAll('.amount-btn');
    
    // 快捷金额按钮
    quickAmountBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const amount = this.dataset.amount;
            if (amount === 'all') {
                const balance = parseFloat(document.getElementById('balance').textContent.replace(',', ''));
                amountInput.value = balance;
            } else {
                amountInput.value = amount;
            }
            
            // 视觉反馈
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
        });
    });
    
    // 表单提交
    if (tradingForm) {
        tradingForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 检查WebSocket连接状态
            if (!wsConnected) {
                showNotification('实时连接未建立，请等待连接成功后再投注', 'warning');
                return;
            }
            
            const amount = parseFloat(amountInput.value);
            if (amount <= 0) {
                showNotification('请输入有效金额', 'error');
                return;
            }
            
            buyPosition(amount);
        });
    }
});

// 买入操作
function buyPosition(amount) {
    // 双重检查WebSocket连接状态
    if (!wsConnected) {
        showNotification('实时连接已断开，无法进行投注', 'error');
        return;
    }
    
    // 计算预估手续费（3%）
    const feeRate = 0.03;
    const fee = amount * feeRate;
    const actualAmount = amount - fee;
    
    // 显示确认对话框，包含手续费信息
    if (!confirm(`确认买入¥${amount.toFixed(2)}吗？\n手续费率：3%\n手续费：¥${fee.toFixed(2)}\n实际买入金额：¥${actualAmount.toFixed(2)}`)) {
        return;
    }
    
    const button = document.getElementById('buy-btn');
    const originalText = button.textContent;
    
    showLoading();
    button.disabled = true;
    button.textContent = '处理中...';
    
    fetch('ajax/trade.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=buy&amount=${amount}`
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        
        if (data.success) {
            // 显示买入成功信息，包含手续费
            const feeInfo = data.fee ? `已扣除手续费¥${data.fee.toFixed(2)}` : '';
            showNotification(`买入成功！${feeInfo}`);
            document.getElementById('amount').value = '';
            updateGameData();
            
            // 触觉反馈 (如果支持)
            if (navigator.vibrate) {
                navigator.vibrate(100);
            }
        } else {
            showNotification('买入失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        hideLoading();
        console.error('交易失败:', error);
        showNotification('网络错误，请重试', 'error');
    })
    .finally(() => {
        button.disabled = false;
        button.textContent = originalText;
    });
}

// 卖出操作
function sellPosition(positionId) {
    // 提示卖出将收取3%手续费
    if (!confirm('确定要卖出这个持仓吗？\n卖出将收取3%的交易手续费\n所有卖出所得（扣除手续费后）将冻结到次日')) {
        return;
    }
    
    showLoading();
    
    fetch('ajax/trade.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=sell&position_id=${positionId}`
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        
        if (data.success) {
            const profitText = data.profit > 0 ? `盈利¥${data.profit.toFixed(2)}` : `亏损¥${Math.abs(data.profit).toFixed(2)}`;
            const feeText = data.fee ? `，手续费¥${data.fee.toFixed(2)}` : '';
            showNotification(`卖出成功！${profitText}${feeText}`);
            updateGameData();
            
            // 触觉反馈
            if (navigator.vibrate) {
                navigator.vibrate([100, 50, 100]);
            }
        } else {
            showNotification('卖出失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        hideLoading();
        console.error('卖出失败:', error);
        showNotification('网络错误，请重试', 'error');
    });
}

// 底部导航
function initBottomNav() {
    const navItems = document.querySelectorAll('.nav-item');
    
    // 初始化时只显示交易页面，隐藏其他页面
    switchSection('trading');
    
    // 设置交易标签页为激活状态
    const tradingTab = document.querySelector('[data-section="trading"]');
    if (tradingTab) {
        tradingTab.classList.add('active');
    }
    
    navItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 如果点击的是当前激活项，添加脉冲动画
            if (this.classList.contains('active')) {
                this.classList.add('nav-pulse');
                setTimeout(() => {
                    this.classList.remove('nav-pulse');
                }, 400);
                return;
            }
            
            // 移除所有active类和动画类
            navItems.forEach(nav => {
                nav.classList.remove('active', 'nav-pulse');
            });
            
            // 添加active类到当前项
            this.classList.add('active');
            
            const section = this.dataset.section;
            switchSection(section);
            
            // 触觉反馈
            if (navigator.vibrate) {
                navigator.vibrate(50);
            }
            
            // 添加切换成功的脉冲动画
            setTimeout(() => {
                this.classList.add('nav-pulse');
                setTimeout(() => {
                    this.classList.remove('nav-pulse');
                }, 400);
            }, 100);
        });
        
        // 添加长按效果
        let pressTimer;
        
        item.addEventListener('touchstart', function(e) {
            pressTimer = setTimeout(() => {
                // 长按效果 - 显示标签提示
                showNavTooltip(this);
                if (navigator.vibrate) {
                    navigator.vibrate([100, 50, 100]);
                }
            }, 500);
        });
        
        item.addEventListener('touchend', function(e) {
            clearTimeout(pressTimer);
        });
        
        item.addEventListener('touchmove', function(e) {
            clearTimeout(pressTimer);
        });
    });
}

// 显示导航提示
function showNavTooltip(navItem) {
    const label = navItem.querySelector('.nav-label').textContent;
    const tooltip = document.createElement('div');
    tooltip.className = 'nav-tooltip';
    tooltip.textContent = label;
    
    // 样式
    tooltip.style.cssText = `
        position: absolute;
        bottom: 80px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0,0,0,0.8);
        color: white;
        padding: 8px 12px;
        border-radius: 8px;
        font-size: 12px;
        z-index: 1001;
        pointer-events: none;
        opacity: 0;
        transition: opacity 0.3s;
    `;
    
    document.body.appendChild(tooltip);
    
    // 计算位置
    const rect = navItem.getBoundingClientRect();
    tooltip.style.left = rect.left + rect.width/2 + 'px';
    
    // 显示动画
    setTimeout(() => {
        tooltip.style.opacity = '1';
    }, 10);
    
    // 2秒后隐藏
    setTimeout(() => {
        tooltip.style.opacity = '0';
        setTimeout(() => {
            if (tooltip.parentNode) {
                tooltip.parentNode.removeChild(tooltip);
            }
        }, 300);
    }, 2000);
}

// 页面切换功能
function switchSection(section) {
    // 首先隐藏所有页面区域
    document.querySelector('.price-section').style.display = 'none';
    document.querySelector('.chart-section').style.display = 'none';
    document.querySelector('.chart-container').style.display = 'none';
    document.querySelector('.market-trades-section').style.display = 'none';
    document.querySelector('.trading-panel').style.display = 'none';
    document.querySelector('.positions-section').style.display = 'none';
    
    const accountSection = document.querySelector('#account-section');
    if (accountSection) {
        accountSection.style.display = 'none';
    }
    
    // 显示对应的页面区域
    switch(section) {
        case 'trading':
            // 显示交易相关区域
            document.querySelector('.price-section').style.display = 'block';
            document.querySelector('.chart-section').style.display = 'block';
            document.querySelector('.chart-container').style.display = 'block';
            document.querySelector('.chart-tabs').style.display = 'block';
            document.querySelector('.market-trades-section').style.display = 'block';
            document.querySelector('.trading-panel').style.display = 'block';
            document.querySelector('.positions-section').style.display = 'none';
            // 加载市场交易记录
            loadRoundTransactions();
            break;
            
        case 'positions':
            // 只显示持仓相关区域
            document.querySelector('.price-section').style.display = 'none';
            document.querySelector('.chart-container').style.display = 'none';
            document.querySelector('.chart-tabs').style.display = 'none';
            document.querySelector('.market-trades-section').style.display = 'none';
            document.querySelector('.trading-panel').style.display = 'none';
            document.querySelector('.positions-section').style.display = 'block';
            break;
            
        case 'account':
            // 显示账户页面，隐藏价格和图表区域
            document.querySelector('.price-section').style.display = 'none';
            document.querySelector('.chart-section').style.display = 'none';
            document.querySelector('.chart-container').style.display = 'none';
            document.querySelector('.chart-tabs').style.display = 'none';
            document.querySelector('.market-trades-section').style.display = 'none';
            document.querySelector('.trading-panel').style.display = 'none';
            document.querySelector('.positions-section').style.display = 'none';
            document.getElementById('account-section').style.display = 'block';
            loadAccountStats();
            break;
    }
}

// 滚动到元素
function scrollToElement(selector) {
    const element = document.querySelector(selector);
    if (element) {
        element.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
}

// 显示加载状态
function showLoading() {
    document.getElementById('loading').style.display = 'flex';
}

// 隐藏加载状态
function hideLoading() {
    document.getElementById('loading').style.display = 'none';
}

// 显示通知消息
function showNotification(message, type = 'success') {
    const notification = document.getElementById('notification');
    notification.textContent = message;
    notification.className = `notification ${type}`;
    notification.style.display = 'block';
    
    // 延迟显示动画
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 3秒后隐藏
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.style.display = 'none';
        }, 300);
    }, 3000);
}

// 页面可见性变化处理
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // 页面不可见时暂停更新
        if (updateInterval) {
            clearInterval(updateInterval);
        }
        // 不清除倒计时定时器，让它继续运行
        console.log('页面不可见，暂停更新但保持倒计时');
    } else {
        // 页面可见时恢复更新
        console.log('页面重新可见，恢复更新');
        startRealTimeUpdates();
        updateGameData(); // 立即更新一次
        
        // 确保倒计时正在运行
        if (!countdownInterval && window.currentRoundInfo) {
            console.log('重新启动倒计时');
            startCountdown();
        }
    }
});

// 页面加载完成后自动启动实时更新
document.addEventListener('DOMContentLoaded', function() {
    // 设置用户信息（如果已登录）
    const usernameElement = document.querySelector('.username');
    if (usernameElement) {
        window.username = usernameElement.textContent;
    }
    
    // 延迟一点启动，确保页面元素都已加载
    setTimeout(() => {
        startRealTimeUpdates();
        updateGameData(); // 立即更新一次游戏数据
        
        // 初始化图表标签页功能
        initChartTabs();
    }, 500);
});

// 页面关闭时清理
window.addEventListener('beforeunload', function() {
    if (updateInterval) {
        clearInterval(updateInterval);
    }
    if (countdownInterval) {
        clearInterval(countdownInterval);
    }
});

// 防止双击缩放
let lastTouchEnd = 0;
document.addEventListener('touchend', function (event) {
    const now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        event.preventDefault();
    }
    lastTouchEnd = now;
}, false);

// 加载账户统计数据
function loadAccountStats() {
    fetch('ajax/get_account_stats.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新统计数据
                document.getElementById('total-trades').textContent = data.total_trades || '0';
                document.getElementById('total-profit').textContent = '¥' + (data.total_profit || '0.00');
                document.getElementById('win-rate').textContent = (data.win_rate || '0') + '%';
                document.getElementById('current-positions').textContent = data.current_positions || '0';
                
                // 更新账户余额（保持同步）
                document.getElementById('account-balance').textContent = parseFloat(data.balance).toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
                
                document.getElementById('account-frozen').textContent = parseFloat(data.frozen_profit).toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
                
                const totalAssets = parseFloat(data.balance) + parseFloat(data.frozen_profit);
                document.getElementById('total-assets').textContent = totalAssets.toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
            }
        })
        .catch(error => {
            console.error('加载账户统计失败:', error);
        });
}

// 显示交易历史
function showTransactionHistory() {
    const modal = document.getElementById('history-modal');
    const historyContainer = document.getElementById('transaction-history');
    
    modal.style.display = 'flex';
    historyContainer.innerHTML = '<div class="loading-text">加载中...</div>';
    
    fetch('ajax/get_transaction_history.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.transactions) {
                if (data.transactions.length === 0) {
                    historyContainer.innerHTML = '<div class="loading-text">暂无交易记录</div>';
                    return;
                }
                
                historyContainer.innerHTML = data.transactions.map(transaction => {
                    const typeClass = transaction.type === 'buy' ? 'buy' : 'sell';
                    const typeText = transaction.type === 'buy' ? '买入' : '卖出';
                    const profitClass = parseFloat(transaction.profit) >= 0 ? 'profit-positive' : 'profit-negative';
                    const profitText = parseFloat(transaction.profit) >= 0 ? '+' : '';
                    
                    return `
                        <div class="transaction-item">
                            <div class="transaction-info">
                                <div class="transaction-type ${typeClass}">${typeText}</div>
                                <div class="transaction-details">
                                    第${transaction.round_number}轮 | ${transaction.quantity}股 | ¥${parseFloat(transaction.price).toFixed(2)}
                                    <br>
                                    ${new Date(transaction.transaction_time).toLocaleString('zh-CN')}
                                </div>
                            </div>
                            <div class="transaction-amount">
                                ¥${parseFloat(transaction.amount).toFixed(2)}
                                <div class="transaction-profit ${profitClass}">
                                    ${profitText}¥${parseFloat(transaction.profit).toFixed(2)}
                                </div>
                            </div>
                        </div>
                    `;
                }).join('');
            } else {
                historyContainer.innerHTML = '<div class="loading-text">加载失败，请重试</div>';
            }
        })
        .catch(error => {
            console.error('加载交易历史失败:', error);
            historyContainer.innerHTML = '<div class="loading-text">加载失败，请重试</div>';
        });
}

// 显示提现记录
function showWithdrawHistory() {
    const modal = document.getElementById('withdraw-history-modal');
    const historyContainer = document.getElementById('withdraw-history');
    
    modal.style.display = 'flex';
    historyContainer.innerHTML = '<div class="loading-text">加载中...</div>';
    
    fetch('ajax/get_withdraw_records.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.records) {
                if (data.records.length === 0) {
                    historyContainer.innerHTML = '<div class="loading-text">暂无提现记录</div>';
                    return;
                }
                
                historyContainer.innerHTML = `
                    <div class="withdraw-records">
                        <table class="withdraw-table">
                            <thead>
                                <tr>
                                    <th>时间</th>
                                    <th>金额</th>
                                    <th>手续费</th>
                                    <th>实际到账</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.records.map(record => {
                                    // 根据状态设置不同的CSS类
                                    let statusClass = '';
                                    switch(record.status) {
                                        case 'completed':
                                            statusClass = 'status-completed';
                                            break;
                                        case 'pending':
                                        case 'processing':
                                            statusClass = 'status-pending';
                                            break;
                                        case 'rejected':
                                        case 'failed':
                                            statusClass = 'status-failed';
                                            break;
                                    }
                                    
                                    return `
                                        <tr>
                                            <td>${record.created_at}</td>
                                            <td>¥${record.amount.toFixed(2)}</td>
                                            <td>¥${record.fee.toFixed(2)}</td>
                                            <td>¥${record.actual_amount.toFixed(2)}</td>
                                            <td class="${statusClass}">${record.status_text}</td>
                                        </tr>
                                    `;
                                }).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                historyContainer.innerHTML = '<div class="loading-text">加载失败</div>';
            }
        })
        .catch(error => {
            console.error('获取提现记录失败:', error);
            historyContainer.innerHTML = '<div class="loading-text">加载失败，请重试</div>';
        });
}

// 关闭模态框
function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// 加载当前轮次的市场交易记录
function loadRoundTransactions() {
    const container = document.getElementById('market-trades');
    
    fetch('ajax/get_round_transactions.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.transactions) {
                if (data.transactions.length === 0) {
                    container.innerHTML = '<div class="loading-text">暂无交易记录</div>';
                    return;
                }
                
                // 显示最新的10条记录
                const transactions = data.transactions.slice(0, 10);
                
                                 container.innerHTML = transactions.map(trade => {
                     const typeClass = trade.type === 'buy' ? 'trade-buy' : 'trade-sell';
                     const typeText = trade.type === 'buy' ? '买入' : '卖出';
                     
                     return `
                         <div class="market-trade-item">
                             <div class="trade-info">
                                 <span class="${typeClass}">${typeText}</span>
                                 <span class="trade-user">${trade.username}</span>
                                 <span class="trade-time" data-original-time="${trade.transaction_time}">${trade.transaction_time}</span>
                             </div>
                             <div class="trade-details">
                                 <span class="trade-amount">¥${trade.amount.toFixed(2)}</span>
                                 <span class="trade-quantity">${trade.quantity.toFixed(4)}股</span>
                             </div>
                         </div>
                     `;
                 }).join('');
                
                // 添加轮次信息
                if (data.round_info) {
                    const roundInfo = document.createElement('div');
                    roundInfo.className = 'round-info-text';
                    roundInfo.textContent = `第${data.round_info.round_number}轮 - ${getStatusText(data.round_info.status)}`;
                    container.prepend(roundInfo);
                }
                
                // 启动时间更新定时器
                startTimeUpdateTimer();
            } else {
                container.innerHTML = '<div class="loading-text">加载失败</div>';
            }
        })
        .catch(error => {
            console.error('加载市场交易记录失败:', error);
            container.innerHTML = '<div class="loading-text">加载失败，请重试</div>';
        });
}

// 获取状态文本
function getStatusText(status) {
    switch(status) {
        case 'trading':
            return '交易中';
        case 'settlement':
            return '结算中';
        case 'break':
            return '休市中';
        default:
            return status;
    }
}

// 确认退出登录
function confirmLogout() {
    if (confirm('确定要退出登录吗？')) {
        window.location.href = 'logout.php';
    }
}

// 点击模态框背景关闭
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal')) {
        e.target.style.display = 'none';
    }
});

// 显示充值弹窗
function showDepositModal() {
    document.getElementById('deposit-modal').style.display = 'flex';
}

// 显示提现弹窗
function showWithdrawModal() {
    // 更新可提现余额
    const balance = parseFloat(document.getElementById('balance').textContent.replace(',', ''));
    document.getElementById('withdrawable-balance').textContent = balance.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
    
    document.getElementById('withdraw-modal').style.display = 'flex';
}

// 初始化充值提现表单
document.addEventListener('DOMContentLoaded', function() {
    // 充值快捷金额按钮
    document.querySelectorAll('.quick-amounts-deposit .quick-amount-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const amount = this.dataset.amount;
            document.getElementById('deposit-amount').value = amount;
        });
    });
    
    // 提现快捷金额按钮
    document.querySelectorAll('.quick-amounts-withdraw .quick-amount-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const amount = this.dataset.amount;
            if (amount === 'all') {
                const balance = parseFloat(document.getElementById('withdrawable-balance').textContent.replace(',', ''));
                document.getElementById('withdraw-amount').value = balance;
            } else {
                document.getElementById('withdraw-amount').value = amount;
            }
        });
    });
    
    // 充值表单提交
    document.getElementById('deposit-form').addEventListener('submit', function(e) {
        e.preventDefault();
        processDeposit();
    });
    
    // 提现表单提交
    document.getElementById('withdraw-form').addEventListener('submit', function(e) {
        e.preventDefault();
        processWithdraw();
    });
});

// 处理充值
function processDeposit() {
    const amount = parseFloat(document.getElementById('deposit-amount').value);
    const paymentMethod = document.getElementById('payment-method').value;
    
    if (!amount || amount <= 0) {
        showNotification('请输入有效的充值金额', 'error');
        return;
    }
    
    if (!paymentMethod) {
        showNotification('请选择支付方式', 'error');
        return;
    }
    
    const submitBtn = document.querySelector('.deposit-submit');
    submitBtn.disabled = true;
    submitBtn.textContent = '创建订单中...';
    showLoading();
    
    // 使用FormData发送请求
    const formData = new FormData();
    formData.append('amount', amount);
    formData.append('payment_method', paymentMethod);
    
    fetch('ajax/deposit.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }
        return response.text().then(text => {
            if (!text) {
                throw new Error('服务器返回空响应');
            }
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON解析错误:', e);
                console.error('原始响应:', text);
                throw new Error('服务器返回无效的JSON数据');
            }
        });
    })
    .then(data => {
        hideLoading();
        
        if (data.success) {
            showNotification('充值订单创建成功！正在跳转支付页面...', 'success');
            closeModal('deposit-modal');
            
            // 打开支付页面，添加返回URL参数
            const currentPage = window.location.pathname.split('/').pop() || 'index.php';
            const paymentUrl = `deposit_payment.php?deposit_id=${data.deposit_id}&return=${encodeURIComponent(currentPage)}`;
            window.location.href = paymentUrl;
            // 清空表单
            document.getElementById('deposit-form').reset();
            
            // 提示用户
            setTimeout(() => {
                showNotification('请在新打开的页面中完成支付，支付时请填写备注码', 'success');
            }, 1000);
            
            // 触觉反馈
            if (navigator.vibrate) {
                navigator.vibrate([100, 50, 100]);
            }
        } else {
            showNotification('创建充值订单失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        hideLoading();
        console.error('创建充值订单失败:', error);
        showNotification('网络错误，请重试', 'error');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.textContent = '确认充值';
    });
}

// 处理提现
function processWithdraw() {
    const amount = parseFloat(document.getElementById('withdraw-amount').value);
    const withdrawMethod = document.getElementById('withdraw-method').value;
    const account = document.getElementById('withdraw-account').value.trim();
    const balance = parseFloat(document.getElementById('withdrawable-balance').textContent.replace(',', ''));
    
    if (!amount || amount <= 0) {
        showNotification('请输入有效的提现金额', 'error');
        return;
    }
    
    if (amount > balance) {
        showNotification('提现金额不能超过可用余额', 'error');
        return;
    }
    
    if (!withdrawMethod) {
        showNotification('请选择提现方式', 'error');
        return;
    }
    
    if (!account) {
        showNotification('请输入收款账号', 'error');
        return;
    }
    
    // 计算阶梯式手续费
    let feeRate;
    if (amount < 100) {
        feeRate = 0.15; // 小于100，15%手续费
    } else if (amount < 500) {
        feeRate = 0.10; // 100-500之间，10%手续费
    } else {
        feeRate = 0.05; // 大于500，5%手续费
    }
    
    const fee = amount * feeRate;
    const actualAmount = amount - fee;
    
    if (!confirm(`确认提现¥${amount.toFixed(2)}吗？\n手续费率：${(feeRate * 100).toFixed(0)}%\n手续费：¥${fee.toFixed(2)}\n实际到账：¥${actualAmount.toFixed(2)}`)) {
        return;
    }
    
    const submitBtn = document.querySelector('.withdraw-submit');
    submitBtn.disabled = true;
    submitBtn.textContent = '处理中...';
    showLoading();
    
    fetch('ajax/withdraw.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `amount=${amount}&withdraw_method=${withdrawMethod}&account=${encodeURIComponent(account)}`
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        
        if (data.success) {
            showNotification(`提现申请成功！预计24小时内到账¥${actualAmount.toFixed(2)}`);
            closeModal('withdraw-modal');
            
            // 清空表单
            document.getElementById('withdraw-form').reset();
            
            // 更新余额显示
            updateGameData();
            
            // 触觉反馈
            if (navigator.vibrate) {
                navigator.vibrate([100, 50, 100]);
            }
        } else {
            showNotification('提现失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        hideLoading();
        console.error('提现失败:', error);
        showNotification('网络错误，请重试', 'error');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.textContent = '确认提现';
    });
}

// 显示修改密码弹窗
function showChangePasswordModal() {
    const modal = document.getElementById('change-password-modal');
    modal.style.display = 'block';
    
    // 清空表单
    document.getElementById('change-password-form').reset();
}

// 处理修改密码表单提交
function initChangePasswordForm() {
    const form = document.getElementById('change-password-form');
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            processChangePassword();
        });
        
        // 设置密码验证
        setupPasswordValidation();
    }
}

// 验证密码强度
function validatePasswordStrength(password) {
    const result = {
        isValid: true,
        messages: []
    };
    
    if (password.length < 6) {
        result.isValid = false;
        result.messages.push('密码长度至少为6位');
    }
    
    if (password.length > 20) {
        result.isValid = false;
        result.messages.push('密码长度不能超过20位');
    }
    
    // 检查是否包含字母
    if (!/[a-zA-Z]/.test(password)) {
        result.messages.push('建议包含字母');
    }
    
    // 检查是否包含数字
    if (!/[0-9]/.test(password)) {
        result.messages.push('建议包含数字');
    }
    
    // 检查是否为常见弱密码
    const weakPasswords = ['123456', '123456789', 'password', '12345678', 'qwerty', 'abc123'];
    if (weakPasswords.includes(password.toLowerCase())) {
        result.isValid = false;
        result.messages.push('密码过于简单，请使用更复杂的密码');
    }
    
    return result;
}

// 实时密码强度检查
function setupPasswordValidation() {
    const newPasswordInput = document.getElementById('new-password');
    const confirmPasswordInput = document.getElementById('confirm-new-password');
    
    if (newPasswordInput) {
        newPasswordInput.addEventListener('input', function() {
            const password = this.value;
            const validation = validatePasswordStrength(password);
            
            // 移除之前的提示
            const existingHint = this.parentNode.querySelector('.password-strength-hint');
            if (existingHint) {
                existingHint.remove();
            }
            
            if (password && validation.messages.length > 0) {
                const hint = document.createElement('div');
                hint.className = 'password-strength-hint';
                hint.innerHTML = validation.messages.map(msg => `<small style="color: ${validation.isValid ? '#f39c12' : '#e74c3c'};">• ${msg}</small>`).join('<br>');
                this.parentNode.appendChild(hint);
            }
        });
    }
    
    if (confirmPasswordInput) {
        confirmPasswordInput.addEventListener('input', function() {
            const password = newPasswordInput.value;
            const confirmPassword = this.value;
            
            // 移除之前的提示
            const existingHint = this.parentNode.querySelector('.password-match-hint');
            if (existingHint) {
                existingHint.remove();
            }
            
            if (confirmPassword && password !== confirmPassword) {
                const hint = document.createElement('div');
                hint.className = 'password-match-hint';
                hint.innerHTML = '<small style="color: #e74c3c;">• 两次输入的密码不一致</small>';
                this.parentNode.appendChild(hint);
            }
        });
    }
}

// 处理修改密码
function processChangePassword() {
    const currentPassword = document.getElementById('current-password').value.trim();
    const newPassword = document.getElementById('new-password').value.trim();
    const confirmPassword = document.getElementById('confirm-new-password').value.trim();
    const submitBtn = document.querySelector('.change-password-submit');
    
    // 前端验证
    if (!currentPassword || !newPassword || !confirmPassword) {
        showNotification('请填写所有字段', 'error');
        return;
    }
    
    // 验证密码强度
    const passwordValidation = validatePasswordStrength(newPassword);
    if (!passwordValidation.isValid) {
        showNotification(passwordValidation.messages[0], 'error');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        showNotification('两次输入的新密码不一致', 'error');
        return;
    }
    
    if (currentPassword === newPassword) {
        showNotification('新密码不能与当前密码相同', 'error');
        return;
    }
    
    // 禁用提交按钮并显示加载状态
    submitBtn.disabled = true;
    submitBtn.textContent = '修改中...';
    showLoading();
    
    // 发送请求
    fetch('ajax/change_password.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            old_password: currentPassword,
            new_password: newPassword,
            confirm_password: confirmPassword
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络请求失败');
        }
        return response.json();
    })
    .then(data => {
        hideLoading();
        
        if (data.success) {
            showNotification(data.message, 'success');
            closeModal('change-password-modal');
            
            // 清空表单
            document.getElementById('change-password-form').reset();
            
            // 清除所有提示信息
            document.querySelectorAll('.password-strength-hint, .password-match-hint').forEach(hint => {
                hint.remove();
            });
            
            // 可选：提示用户重新登录
            setTimeout(() => {
                if (confirm('密码修改成功！为了安全起见，建议您重新登录，是否现在登录？')) {
                    window.location.href = 'logout.php';
                }
            }, 2000);
        } else {
            showNotification(data.message, 'error');
        }
    })
    .catch(error => {
        hideLoading();
        console.error('修改密码失败:', error);
        showNotification('网络错误，请重试', 'error');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.textContent = '确认修改';
    });
}

// K线图功能

// 初始化图表切换功能
function initChartTabs() {
    const chartTabs = document.querySelectorAll('.chart-tab');
    const priceChartContainer = document.getElementById('price-chart-container');
    const klineChartContainer = document.getElementById('kline-chart-container');
    
    chartTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const chartType = this.getAttribute('data-chart');
            
            // 更新标签样式
            chartTabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            
            // 显示/隐藏对应的图表
            if (chartType === 'price') {
                priceChartContainer.style.display = 'block';
                klineChartContainer.style.display = 'none';
            } else if (chartType === 'kline') {
                priceChartContainer.style.display = 'none';
                klineChartContainer.style.display = 'block';
                // 首次切换到K线图时初始化
                initKlineChart();
            }
        });
    });
}

// 初始化K线图功能
function initKlineChart() {
    console.log('初始化K线图功能');
    
    // 初始化每日K线图
    initDailyKlineChart();
}

// 初始化每日K线图
function initDailyKlineChart() {
    console.log('初始化每日K线图');
    
    // 加载今天的K线数据
    const today = new Date().toISOString().split('T')[0];
    loadDailyKlineData(today);
    
    // 绑定日期筛选器事件
    const dateFilter = document.getElementById('date-filter');
    if (dateFilter) {
        dateFilter.addEventListener('change', function() {
            const selectedDate = this.value;
            console.log('日期筛选器变化:', selectedDate);
            
            // 根据选择的日期加载数据
            let targetDate = today;
            switch (selectedDate) {
                case 'yesterday':
                    const yesterday = new Date();
                    yesterday.setDate(yesterday.getDate() - 1);
                    targetDate = yesterday.toISOString().split('T')[0];
                    break;
                case 'week':
                    const weekAgo = new Date();
                    weekAgo.setDate(weekAgo.getDate() - 7);
                    targetDate = weekAgo.toISOString().split('T')[0];
                    break;
                case 'month':
                    const monthAgo = new Date();
                    monthAgo.setDate(monthAgo.getDate() - 30);
                    targetDate = monthAgo.toISOString().split('T')[0];
                    break;
                case 'all':
                    targetDate = 'all';
                    break;
            }
            
            console.log('目标日期:', targetDate);
            loadDailyKlineData(targetDate);
        });
    }
}

// 加载每日K线数据
function loadDailyKlineData(date, days = 1) {
    console.log('加载每日K线数据:', date, '天数:', days);
    
    showLoading();
    
    fetch(`ajax/get_kline_data.php?action=daily_kline&date=${date}`)
        .then(response => response.json())
        .then(data => {
            hideLoading();
            
            console.log('每日K线数据响应:', data);
            
            if (data.success) {
                if (data.kline_data && data.kline_data.length > 0) {
                    console.log('每日K线数据条数:', data.kline_data.length);
                    console.log('第一条K线数据:', data.kline_data[0]);
                    console.log('汇总数据:', data.summary);
                    
                    // 渲染每日K线图
                    renderDailyKlineChart(data);
                    showDailyKlineInfo(data);
                } else {
                    console.warn('每日K线数据为空');
                    hideDailyKlineInfo();
                    showNotification('该日期暂无K线数据', 'info');
                }
            } else {
                console.error('每日K线数据加载失败:', data.message);
                showNotification(data.message || '每日K线数据加载失败', 'error');
            }
        })
        .catch(error => {
            hideLoading();
            console.error('加载每日K线数据失败:', error);
            showNotification('加载每日K线数据失败', 'error');
        });
}

// 日期筛选器变化处理
function onDateFilterChange() {
    const dateFilter = document.getElementById('date-filter');
    const filter = dateFilter.value;
    
    // 根据选择的日期加载数据
    const today = new Date().toISOString().split('T')[0];
    if (filter === 'today') {
        loadDailyKlineData(today);
    } else if (filter === 'yesterday') {
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        loadDailyKlineData(yesterday.toISOString().split('T')[0]);
    } else if (filter === 'week' || filter === 'month' || filter === 'all') {
        loadDailyKlineData(today, filter === 'week' ? 7 : 30);
    }
}

// 渲染每日K线图
function renderDailyKlineChart(data) {
    if (!data || !data.kline_data) {
        console.log('每日K线数据为空');
        return;
    }
    
    console.log('渲染每日K线图:', data);
    
    // 显示汇总信息
    showDailyKlineInfo(data);
    
    // 使用原生Canvas绘制K线图
    drawKlineOnCanvas('nativeKlineCanvas', data.kline_data);
    
    // 强制重新绘制，确保Canvas正确显示
    setTimeout(() => {
        const canvas = document.getElementById('nativeKlineCanvas');
        if (canvas && canvas.touchData) {
            // 重新绘制K线图
            drawKlineOnCanvas('nativeKlineCanvas', data.kline_data);
        }
    }, 200);
}

// 显示每日K线图信息
function showDailyKlineInfo(data) {
    const infoContainer = document.getElementById('dailyKlineInfo');
    if (!infoContainer) return;
    
    // 更新汇总信息
    const totalRounds = document.getElementById('dailyTotalRounds');
    const avgOpen = document.getElementById('dailyAvgOpen');
    const avgClose = document.getElementById('dailyAvgClose');
    const dailyHigh = document.getElementById('dailyHigh');
    const dailyLow = document.getElementById('dailyLow');
    
    if (totalRounds) totalRounds.textContent = data.summary.total_rounds || 0;
    if (avgOpen) avgOpen.textContent = `¥${parseFloat(data.summary.avg_open || 0).toFixed(2)}`;
    if (avgClose) avgClose.textContent = `¥${parseFloat(data.summary.avg_close || 0).toFixed(2)}`;
    if (dailyHigh) dailyHigh.textContent = `¥${parseFloat(data.summary.high || 0).toFixed(2)}`;
    if (dailyLow) dailyLow.textContent = `¥${parseFloat(data.summary.low || 0).toFixed(2)}`;
    
    infoContainer.style.display = 'block';
}

// 隐藏每日K线图信息
function hideDailyKlineInfo() {
    const infoContainer = document.getElementById('dailyKlineInfo');
    if (infoContainer) {
        infoContainer.style.display = 'none';
    }
}

function drawKlineOnCanvas(canvasId, klineData) {
    console.log('开始绘制K线图:', canvasId, '数据条数:', klineData ? klineData.length : 0);
    
    const canvas = document.getElementById(canvasId);
    if (!canvas) {
        console.error('Canvas元素未找到:', canvasId);
        return;
    }
    
    if (!klineData || klineData.length === 0) {
        console.error('K线数据为空');
        return;
    }
    
    const ctx = canvas.getContext('2d');
    
    // 设置画布尺寸
    const rect = canvas.getBoundingClientRect();
    if (rect.width > 0 && rect.height > 0) {
        canvas.width = rect.width;
        canvas.height = rect.height;
        console.log('Canvas尺寸已设置:', canvas.width, 'x', canvas.height);
    } else {
        canvas.width = 800;
        canvas.height = 400;
        console.log('使用默认Canvas尺寸:', canvas.width, 'x', canvas.height);
    }
    
    // 添加触摸滑动和缩放功能
    if (!canvas.touchData) {
        canvas.touchData = {
            startX: 0,
            currentX: 0,
            offsetX: 0,
            isDragging: false,
            scale: 1,
            minScale: 0.3,
            maxScale: 5,
            lastTouchDistance: 0,
            isScaling: false,
            lastTapTime: 0,
            velocity: 0,
            lastMoveTime: 0
        };
        
        // 触摸事件处理
        canvas.addEventListener('touchstart', function(e) {
            e.preventDefault();
            
            if (e.touches.length === 1) {
                const touch = e.touches[0];
                canvas.touchData.startX = touch.clientX;
                canvas.touchData.isDragging = true;
                canvas.touchData.isScaling = false;
                canvas.touchData.lastMoveTime = Date.now();
            } else if (e.touches.length === 2) {
                canvas.touchData.isDragging = false;
                canvas.touchData.isScaling = true;
                canvas.touchData.lastTouchDistance = getTouchDistance(e.touches);
            }
        });
        
        canvas.addEventListener('touchmove', function(e) {
            e.preventDefault();
            
            if (e.touches.length === 1 && canvas.touchData.isDragging) {
                const touch = e.touches[0];
                const deltaX = touch.clientX - canvas.touchData.startX;
                const currentTime = Date.now();
                const timeDelta = currentTime - canvas.touchData.lastMoveTime;
                
                if (timeDelta > 0) {
                    canvas.touchData.velocity = deltaX / timeDelta;
                }
                
                canvas.touchData.offsetX += deltaX;
                canvas.touchData.startX = touch.clientX;
                canvas.touchData.lastMoveTime = currentTime;
                
                const maxOffset = Math.max(0, (klineData.length * 10 * canvas.touchData.scale) - canvas.width + 60);
                canvas.touchData.offsetX = Math.max(-maxOffset, Math.min(0, canvas.touchData.offsetX));
                
                drawKlineContent();
            } else if (e.touches.length === 2 && canvas.touchData.isScaling) {
                const currentDistance = getTouchDistance(e.touches);
                const scaleChange = currentDistance / canvas.touchData.lastTouchDistance;
                
                canvas.touchData.scale *= scaleChange;
                canvas.touchData.scale = Math.max(canvas.touchData.minScale, 
                                                Math.min(canvas.touchData.maxScale, canvas.touchData.scale));
                
                canvas.touchData.lastTouchDistance = currentDistance;
                drawKlineContent();
            }
        });
        
        canvas.addEventListener('touchend', function(e) {
            if (canvas.touchData.isDragging) {
                if (Math.abs(canvas.touchData.velocity) > 0.5) {
                    const inertia = canvas.touchData.velocity * 100;
                    canvas.touchData.offsetX += inertia;
                    
                    const maxOffset = Math.max(0, (klineData.length * 10 * canvas.touchData.scale) - canvas.width + 60);
                    canvas.touchData.offsetX = Math.max(-maxOffset, Math.min(0, canvas.touchData.offsetX));
                    
                    let deceleration = 0.95;
                    const animateInertia = () => {
                        canvas.touchData.velocity *= deceleration;
                        canvas.touchData.offsetX += canvas.touchData.velocity * 10;
                        
                        canvas.touchData.offsetX = Math.max(-maxOffset, Math.min(0, canvas.touchData.offsetX));
                        
                        drawKlineContent();
                        
                        if (Math.abs(canvas.touchData.velocity) > 0.1) {
                            requestAnimationFrame(animateInertia);
                        }
                    };
                    animateInertia();
                }
            }
            
            canvas.touchData.isDragging = false;
            canvas.touchData.isScaling = false;
            canvas.touchData.velocity = 0;
        });
        
        // 双击缩放
        canvas.addEventListener('touchend', function(e) {
            const currentTime = Date.now();
            const timeSinceLastTap = currentTime - canvas.touchData.lastTapTime;
            
            if (timeSinceLastTap < 300) {
                if (canvas.touchData.scale > 1.1) {
                    canvas.touchData.scale = 1;
                    canvas.touchData.offsetX = 0;
                } else {
                    canvas.touchData.scale = 2;
                }
                drawKlineContent();
            }
            canvas.touchData.lastTapTime = currentTime;
        });
        
        // 鼠标事件处理
        canvas.addEventListener('mousedown', function(e) {
            canvas.touchData.startX = e.clientX;
            canvas.touchData.isDragging = true;
        });
        
        canvas.addEventListener('mousemove', function(e) {
            if (!canvas.touchData.isDragging) return;
            
            const deltaX = e.clientX - canvas.touchData.startX;
            canvas.touchData.offsetX += deltaX;
            canvas.touchData.startX = e.clientX;
            
            const maxOffset = Math.max(0, (klineData.length * 10 * canvas.touchData.scale) - canvas.width + 60);
            canvas.touchData.offsetX = Math.max(-maxOffset, Math.min(0, canvas.touchData.offsetX));
            
            drawKlineContent();
        });
        
        canvas.addEventListener('mouseup', function(e) {
            canvas.touchData.isDragging = false;
        });
        
        canvas.addEventListener('mouseleave', function(e) {
            canvas.touchData.isDragging = false;
        });
        
        // 鼠标滚轮缩放
        canvas.addEventListener('wheel', function(e) {
            e.preventDefault();
            
            const rect = canvas.getBoundingClientRect();
            const mouseX = e.clientX - rect.left;
            const zoomPoint = mouseX - canvas.touchData.offsetX;
            
            const scaleChange = e.deltaY > 0 ? 0.9 : 1.1;
            const oldScale = canvas.touchData.scale;
            canvas.touchData.scale *= scaleChange;
            canvas.touchData.scale = Math.max(canvas.touchData.minScale, 
                                            Math.min(canvas.touchData.maxScale, canvas.touchData.scale));
            
            const scaleRatio = canvas.touchData.scale / oldScale;
            canvas.touchData.offsetX = mouseX - zoomPoint * scaleRatio;
            
            drawKlineContent();
        });
        
        // 双击鼠标缩放
        canvas.addEventListener('dblclick', function(e) {
            if (canvas.touchData.scale > 1.1) {
                canvas.touchData.scale = 1;
                canvas.touchData.offsetX = 0;
            } else {
                canvas.touchData.scale = 2;
            }
            drawKlineContent();
        });
    }
    
    // 重置滑动位置和缩放
    canvas.touchData.offsetX = 0;
    canvas.touchData.scale = 1;
    
    // 计算触摸点距离
    function getTouchDistance(touches) {
        const dx = touches[0].clientX - touches[1].clientX;
        const dy = touches[0].clientY - touches[1].clientY;
        return Math.sqrt(dx * dx + dy * dy);
    }
    
    // 绘制K线内容
    function drawKlineContent() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        if (!klineData || klineData.length === 0) {
            ctx.fillStyle = "#f5f5f5";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            ctx.fillStyle = "#999";
            ctx.font = "16px Arial";
            ctx.textAlign = "center";
            ctx.fillText("暂无K线数据", canvas.width / 2, canvas.height / 2);
            return;
        }
        
        // 计算最大最小价格
        const allPrices = klineData.flatMap(item => [item.open, item.close, item.high, item.low]);
        const maxPrice = Math.max(...allPrices);
        const minPrice = Math.min(...allPrices);
        const priceRange = maxPrice - minPrice;
        
        console.log('价格范围:', minPrice, '到', maxPrice, '范围:', priceRange);
        
        // 添加价格范围缓冲
        const buffer = priceRange * 0.05;
        const adjustedMaxPrice = maxPrice + buffer;
        const adjustedMinPrice = Math.max(0, minPrice - buffer);
        
        // 画布边距和K线设置
        const padding = 30;
        const w = canvas.width, h = canvas.height;
        const baseCandleWidth = 4;
        const baseGap = 10;
        
        const candleWidth = Math.max(1, baseCandleWidth * canvas.touchData.scale);
        const gap = Math.max(4, baseGap * canvas.touchData.scale);
        
        console.log('K线设置:', '宽度:', candleWidth, '间隔:', gap, '缩放:', canvas.touchData.scale);
        
        // 计算可见的K线范围
        const startIndex = Math.floor(-canvas.touchData.offsetX / gap);
        const visibleCount = Math.ceil(w / gap) + 4;
        const endIndex = Math.min(klineData.length, startIndex + visibleCount);
        
        console.log('可见范围:', startIndex, '到', endIndex, '总共:', endIndex - startIndex);
        
        // 坐标转换函数
        function priceToY(price) {
            return padding + (h - 2 * padding) * (1 - (price - adjustedMinPrice) / (adjustedMaxPrice - adjustedMinPrice));
        }
        
        // 绘制背景网格
        drawGrid();
        
        // 绘制坐标轴
        drawAxes();
        
        // 绘制可见的K线
        drawKlines(startIndex, endIndex);
        
        // 绘制价格刻度和标签
        drawPriceLabels();
        
        // 绘制缩放和滑动指示器
        drawScrollIndicator();
        drawScaleIndicator();
        
        // 绘制网格
        function drawGrid() {
            ctx.strokeStyle = "rgba(0,0,0,0.05)";
            ctx.lineWidth = 0.5;
            
            // 水平网格线
            for (let i = 0; i <= 5; i++) {
                const y = padding + (h - 2 * padding) * (i / 5);
                ctx.beginPath();
                ctx.moveTo(padding, y);
                ctx.lineTo(w - padding, y);
                ctx.stroke();
            }
            
            // 垂直网格线
            const gridDensity = Math.max(1, Math.floor(10 / canvas.touchData.scale));
            for (let i = startIndex; i < endIndex; i += gridDensity) {
                if (i < 0 || i >= klineData.length) continue;
                const x = padding + (i * gap) + canvas.touchData.offsetX + gap / 2;
                if (x >= padding && x <= w - padding) {
                    ctx.beginPath();
                    ctx.moveTo(x, padding);
                    ctx.lineTo(x, h - padding);
                    ctx.stroke();
                }
            }
        }
        
        // 绘制坐标轴
        function drawAxes() {
            ctx.strokeStyle = "#333";
            ctx.lineWidth = 2;
            
            // Y轴
            ctx.beginPath();
            ctx.moveTo(padding, padding);
            ctx.lineTo(padding, h - padding);
            ctx.stroke();
            
            // X轴
            ctx.beginPath();
            ctx.moveTo(padding, h - padding);
            ctx.lineTo(w - padding, h - padding);
            ctx.stroke();
        }
        
        // 绘制K线
        function drawKlines(startIdx, endIdx) {
            let drawnCount = 0;
            
            for (let i = startIdx; i < endIdx; i++) {
                if (i < 0 || i >= klineData.length) {
                    continue;
                }
                
                const item = klineData[i];
                
                const x = padding + (i * gap) + canvas.touchData.offsetX + gap / 2;
                
                // 只绘制在画布内的K线
                if (x < padding - candleWidth || x > w - padding + candleWidth) {
                    continue;
                }
                
                const yOpen = priceToY(item.open);
                const yClose = priceToY(item.close);
                const yHigh = priceToY(item.high);
                const yLow = priceToY(item.low);
                
                
                // 颜色方案
                const isUp = item.close >= item.open;
                const mainColor = isUp ? "#e74c3c" : "#27ae60";
                
                ctx.strokeStyle = mainColor;
                ctx.fillStyle = mainColor;
                ctx.lineWidth = Math.max(1, Math.min(3, canvas.touchData.scale));
                
                // 绘制影线
                ctx.beginPath();
                ctx.moveTo(x, yHigh);
                ctx.lineTo(x, yLow);
                ctx.stroke();
                
                // 绘制实体
                const rectY = Math.min(yOpen, yClose);
                const rectH = Math.max(2, Math.abs(yOpen - yClose));
                
                
                ctx.fillRect(x - candleWidth / 2, rectY, candleWidth, rectH);
                
                                 // 绘制轮次标签
                 const labelInterval = Math.max(1, Math.floor(8 / canvas.touchData.scale));
                 if (i % labelInterval === 0) {
                     ctx.fillStyle = "#666";
                     ctx.font = "12px Arial";
                     ctx.textAlign = "center";
                     ctx.fillText(`${item.round_number}`, x, h - padding + 20);
                 }
                
                drawnCount++;
            }
        }
        
                 // 绘制价格标签
         function drawPriceLabels() {
             ctx.fillStyle = "#333";
             ctx.font = "14px Arial";
             ctx.textAlign = "right";
            
            // Y轴价格标签
            for (let i = 0; i <= 5; i++) {
                const price = adjustedMinPrice + (adjustedMaxPrice - adjustedMinPrice) * (i / 5);
                const y = padding + (h - 2 * padding) * (1 - i / 5);
                
                let priceText;
                if (price >= 1000) {
                    priceText = (price / 1000).toFixed(1) + 'K';
                } else {
                    priceText = price.toFixed(2);
                }
                
                ctx.fillText(`¥${priceText}`, padding - 8, y + 4);
            }
        }
    }
    
    // 绘制滑动指示器
    function drawScrollIndicator() {
        const totalWidth = klineData.length * 10 * canvas.touchData.scale;
        const visibleWidth = canvas.width - 80;
        const scrollRatio = Math.abs(canvas.touchData.offsetX) / Math.max(1, totalWidth - visibleWidth);
        
        if (totalWidth > visibleWidth) {
            const indicatorWidth = 80;
            const indicatorHeight = 8;
            const indicatorX = 40;
            const indicatorY = canvas.height - 45;
            
            // 背景条
            ctx.fillStyle = "rgba(0,0,0,0.1)";
            ctx.fillRect(indicatorX, indicatorY, indicatorWidth, indicatorHeight);
            
            // 滑块
            const sliderWidth = Math.max(15, (visibleWidth / totalWidth) * indicatorWidth);
            const sliderX = indicatorX + scrollRatio * (indicatorWidth - sliderWidth);
            
            const gradient = ctx.createLinearGradient(sliderX, indicatorY, sliderX + sliderWidth, indicatorY);
            gradient.addColorStop(0, "#4caf50");
            gradient.addColorStop(1, "#45a049");
            
            ctx.fillStyle = gradient;
            ctx.fillRect(sliderX, indicatorY, sliderWidth, indicatorHeight);
            
            // 圆角效果
            ctx.fillStyle = "rgba(255,255,255,0.3)";
            ctx.fillRect(sliderX, indicatorY, sliderWidth, 2);
        }
    }
    
    // 绘制缩放指示器
    function drawScaleIndicator() {
        const indicatorWidth = 80;
        const indicatorHeight = 8;
        const indicatorX = 40;
        const indicatorY = canvas.height - 25;
        
        // 背景条
        ctx.fillStyle = "rgba(0,0,0,0.1)";
        ctx.fillRect(indicatorX, indicatorY, indicatorWidth, indicatorHeight);
        
        // 缩放滑块
        const scaleRatio = (canvas.touchData.scale - canvas.touchData.minScale) / 
                          (canvas.touchData.maxScale - canvas.touchData.minScale);
        const sliderWidth = 15;
        const sliderX = indicatorX + scaleRatio * (indicatorWidth - sliderWidth);
        
        const gradient = ctx.createLinearGradient(sliderX, indicatorY, sliderX + sliderWidth, indicatorY);
        gradient.addColorStop(0, "#ff9800");
        gradient.addColorStop(1, "#f57c00");
        
        ctx.fillStyle = gradient;
        ctx.fillRect(sliderX, indicatorY, sliderWidth, indicatorHeight);
        
        // 添加提示文字
        ctx.fillStyle = "#666";
        ctx.font = "11px Arial";
        ctx.textAlign = "center";
        ctx.fillText(`缩放: ${canvas.touchData.scale.toFixed(1)}x | 左右滑动查看更多`, canvas.width / 2, indicatorY - 8);
        
        // 添加操作提示
        ctx.font = "10px Arial";
        ctx.fillStyle = "#999";
        ctx.fillText("双指缩放 | 双击重置 | 滚轮缩放", canvas.width / 2, indicatorY + 20);
    }
    
    // 初始绘制
    drawKlineContent();
}

// 更新WebSocket连接状态指示器
function updateWebSocketStatus(status, text) {
    const indicator = document.getElementById('status-indicator');
    const statusText = document.getElementById('status-text');
    const statusContainer = document.querySelector('.websocket-status');
    
    if (!indicator || !statusText || !statusContainer) return;
    
    // 移除所有状态类
    indicator.className = 'status-indicator';
    statusContainer.className = 'websocket-status';
    
    // 根据状态设置样式和文本
    switch(status) {
        case 'connected':
            indicator.classList.add('connected');
            statusContainer.classList.add('connected');
            statusText.textContent = text;
            // 添加连接成功的视觉反馈
            showConnectionSuccess();
            break;
        case 'connecting':
            indicator.classList.add('connecting');
            statusContainer.classList.add('connecting');
            statusText.textContent = text;
            break;
        case 'disconnected':
            indicator.classList.add('disconnected');
            statusContainer.classList.add('disconnected');
            statusText.textContent = text;
            // 添加断开连接的视觉反馈
            showConnectionLost();
            break;
        case 'error':
            indicator.classList.add('error');
            statusContainer.classList.add('error');
            statusText.textContent = text;
            // 添加错误状态的视觉反馈
            showConnectionError();
            break;
        case 'failed':
            indicator.classList.add('failed');
            statusContainer.classList.add('failed');
            statusText.textContent = text;
            break;
        default:
            indicator.classList.add('connecting');
            statusContainer.classList.add('connecting');
            statusText.textContent = '连接中...';
    }
}

// 显示连接成功的视觉反馈
function showConnectionSuccess() {
    const statusContainer = document.querySelector('.websocket-status');
    if (statusContainer) {
        // 添加成功动画
        statusContainer.style.transform = 'scale(1.05)';
        statusContainer.style.boxShadow = '0 0 20px rgba(76, 175, 80, 0.8)';
        
        setTimeout(() => {
            statusContainer.style.transform = 'scale(1)';
            statusContainer.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)';
        }, 300);
        
        // 显示成功通知
        showNotification('实时连接已建立', 'success');
    }
}

// 显示连接断开的视觉反馈
function showConnectionLost() {
    const statusContainer = document.querySelector('.websocket-status');
    if (statusContainer) {
        // 添加断开动画
        statusContainer.style.transform = 'scale(0.95)';
        statusContainer.style.boxShadow = '0 0 20px rgba(244, 67, 54, 0.8)';
        
        setTimeout(() => {
            statusContainer.style.transform = 'scale(1)';
            statusContainer.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)';
        }, 300);
        
        // 显示断开通知
        showNotification('实时连接已断开', 'warning');
    }
}

// 显示连接错误的视觉反馈
function showConnectionError() {
    const statusContainer = document.querySelector('.websocket-status');
    if (statusContainer) {
        // 添加错误动画
        statusContainer.style.transform = 'scale(0.95)';
        statusContainer.style.boxShadow = '0 0 20px rgba(244, 67, 54, 0.8)';
        
        setTimeout(() => {
            statusContainer.style.transform = 'scale(1)';
            statusContainer.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)';
        }, 300);
        
        // 显示错误通知
        showNotification('连接出现错误', 'error');
    }
}


